package com.thc.controller;

import com.thc.blockhandler.ExceptionUtil;
import com.thc.domin.User;
import com.thc.service.IUserService;
import com.thc.userfallback.UserfallBack;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

//用户服务：暴露接口给订单访问
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    //加载端口
    //@Value("${server.port}")
    //private int port;

    @SentinelResource(
            //配置Sentinel限流熔断的注解方法,这方法在限流或者熔断后执行
            value="userSentinel",blockHandler="exceptionHandler"
            ,blockHandlerClass= ExceptionUtil.class,
            //处理异常的类和方法
            fallback = "uesrgetByIdfallback", //方法
            fallbackClass= UserfallBack.class //异常的类
                )
    @GetMapping("/user/{id}")
    public User findById(@PathVariable("id")Long id){


        int i1 = new Random().nextInt(2);
        if(i1 == 0){
            int i = 1 / 0;	//方法异常，触发熔断
        }
        //根据id去数据库查询User
        User user = userService.findById(id);
        return  user;
    }
}